$('.login').on('click', function () {
    location.href = '../login.html'
})

$('form').on('submit', function () {
    var username = $('[name="username"]').val()
    var password = $('[name="password"]').val()
    var rpassword = $('[name="rpassword"]').val()
    var nickname = $('[name="nickname"]').val()
    var sex = $('[name="sex"]').val()
    var age = $('[name="age"]').val()
    var identity = $('[name="identity"]').val()
    //表单校验
    var reg1 = /^[a-z0-9]\w{4,11}$/;
    if (!reg1.test(username)) {
        layer.msg('用户名不规范', {
            icon: 2,
            time: 1000
        })
        return false
    }
    //校验密码
    var reg2 = /\w{6,12}/;
    if (!reg2.test(password)) {
        layer.msg('密码不规范', {
            icon: 2,
            time: 1000
        })
        return false
    }
    //两次密码输入
    if (password !== rpassword) {
        layer.msg('两次密码输入不一致', {
            icon: 2,
            time: 1000
        })
        return false
    }
    //验证昵称
    if (nickname === '') {
        layer.msg('昵称不能为空', {
            icon: 2,
            time: 1000
        })
        return false
    }
    //校验性别
    if (sex !== '男' && sex !== '女') {
        layer.msg('性别请输入男或女', {
            icon: 2,
            time: 1000
        })
        return false
    }
    var xhr = new XMLHttpRequest;
    xhr.open('post', '/api/register');
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    xhr.send(`username=${username}&password=${password}&nickname=${nickname}&sex=${sex}&age=${age}&identity=${identity}`)
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                var res = xhr.responseText;
                res = JSON.parse(res)
                console.log(res);
                if (res.code == 1) {
                    layer.msg(res.msg, {
                        icon: 1,
                        time: 1000
                    }, () => {
                        location.href = '../login.html'
                    })
                } else {
                    layer.msg(res.msg, {
                        icon: 2,
                        time: 1000
                    }, () => {
                        $('[name="username"]').val('')
                        $('[name="password"]').val('')
                        $('[name="rpassword"]').val('')
                        $('[name="nickname"]').val('')
                        $('[name="sex"]').val('')
                        $('[name="age"]').val('')
                        $('[name="identity"]').val('')

                    })
                    return false
                }
            }
        }
    }

    //阻止默认行为
    return false
})

